<template>
  <el-dialog
    class="add-inspection-detail-modal"
    :title="title"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(950)"
    :before-close="handleCancel">
    <div class="form-container">
      <el-form
        :model="ruleForm"
        :rules="rules"
        size="medium"
        ref="ruleForm"
        class="rule-form"
        :label-width="$setRem(160)"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item class="tree-form" label="检查区域" prop="areaName" required>
              <el-input
                placeholder="请选择检查区域"
                :disabled="hasDisabled"
                :value="ruleForm.areaName">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="location-form" label="区域定位" prop="areaName">
              <add-location
                :has-altitude="false"
                :disabled="hasDisabled"
                :value="ruleForm.point">
              </add-location>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="检查时间" prop="inspectDate" required>
              <el-date-picker
                v-model="ruleForm.inspectDate"
                :disabled="hasDisabled"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择检查时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="严重程度" prop="severityLevel" required>
              <el-select
                placeholder="请选择严重程度"
                v-model="ruleForm.severityLevel"
                :disabled="hasDisabled">
                <el-option
                  v-for="key in Object.keys(levels)"
                  :label="levels[key]"
                  :value="key"
                  :key="key">
                  {{ levels[key] }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="整改问题及要求" prop="rectifyProblem">
              <el-input
                type="textarea"
                placeholder="请输入"
                :rows="3"
                :title="ruleForm.rectifyProblem"
                :disabled="hasDisabled"
                v-model="ruleForm.rectifyProblem">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="问题附件" prop="rectifyFile">
            <div class="file-list" v-if="ruleForm.fileList.length">
              <div class="file-text" v-for="fileUrl in ruleForm.fileList" :key="fileUrl">
                <span
                  class="file-name"
                  :title="files(fileUrl).name"
                  @click="handleUpload(fileUrl)">
                  {{ files(fileUrl).name }}
                </span>
                <i v-if="!hasDisabled" class="el-icon-delete file-delete" @click="handleRemove(fileUrl)"></i>
              </div>
            </div>
            <span v-else>--</span>
          </el-form-item>
        </el-row>

        <template v-if="hasDetail">
          <el-row>
            <el-col :span="12">
              <el-form-item label="发起人">
                <el-input disabled :value="details.createrUserName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="整改期限">
                <el-input disabled :value="details.rectifyDate"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <template v-if="Object.keys(newRectify).length">
            <el-row >
              <el-col :span="24">
                <el-form-item label="整改回复">
                  <el-input
                    type="textarea"
                    :rows="3"
                    disabled
                    :value="newRectify.content">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="整改附件">
                <div class="file-list" v-if="newRectify.fileList.length">
                  <div class="file-text" v-for="fileUrl in newRectify.fileList" :key="fileUrl">
                      <span
                        class="file-name"
                        :title="files(fileUrl).name"
                        @click="handleUpload(fileUrl)">
                        {{ files(fileUrl).name }}
                      </span>
                  </div>
                </div>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="整改人">
                  <el-input disabled :value="newRectify.operatUserName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="整改日期">
                  <el-input disabled :value="newRectify.date"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
          <template v-if="Object.keys(newReview).length">
            <el-row >
              <el-col :span="24">
                <el-form-item label="复核意见">
                  <el-input
                    type="textarea"
                    :rows="3"
                    disabled
                    :title="newReview.content"
                    :value="newReview.content">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="newReview.fileList.length">
              <el-form-item label="复核附件">
                <div class="file-list">
                  <div class="file-text" v-for="fileUrl in newReview.fileList" :key="fileUrl">
                      <span
                        class="file-name"
                        :title="files(fileUrl).name"
                        @click="handleUpload(fileUrl)">
                        {{ files(fileUrl).name }}
                      </span>
                  </div>
                </div>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="复核人">
                  <el-input disabled :value="newReview.operatUserName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="复核日期">
                  <el-input disabled :value="newReview.date"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
          <el-row>
            <el-col :span="['1', '0'].includes(status) ? 12 : 24">
              <el-form-item label="抄送人">
                <el-input
                  placeholder="暂无抄送人"
                  disabled
                  :title="ruleForm.cuserName"
                  :value="ruleForm.cuserName">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="通知方式">
              <el-checkbox :value="ruleForm.notifyFlag">手机短信</el-checkbox>
            </el-form-item>
          </el-row>
        </template>

        <template v-else>
          <el-row>
            <el-col :span="24">
              <el-form-item label="整改期限" prop="rectifyDate" required>
                <el-date-picker
                  v-model="ruleForm.rectifyDate"
                  :disabled="hasDisabled"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="请选择整改期限">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="整改回复" prop="content" required>
                <el-input
                  type="textarea"
                  :disabled="!rectification"
                  placeholder="请输入整改回复"
                  :rows="3"
                  v-model="ruleForm.content">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="整改回复附件" prop="annexUrl">
              <el-upload
                v-if="rectification"
                ref="upload"
                :limit="1"
                action="#"
                :multiple="false"
                :on-change="handleChange"
                :file-list="[]"
                :show-file-list="false"
                :auto-upload="false">
                <el-button
                  slot="trigger"
                  :loading="fileLoading"
                  size="small"
                  icon="el-icon-upload2"
                  type="primary">
                  选取文件
                </el-button>
                <span v-if="rectification" class="tip">{{ ruleForm.annexFileList.length }}个文件已上传</span>
              </el-upload>
              <div class="file-list" v-if="ruleForm.annexFileList.length">
                <div class="file-text" v-for="fileUrl in ruleForm.annexFileList" :key="fileUrl">
                    <span
                      class="file-name"
                      :title="files(fileUrl).name"
                      @click="handleUpload(fileUrl)">
                      {{ files(fileUrl).name }}
                    </span>
                  <i v-if="rectification" class="el-icon-delete file-delete" @click="handleRemove(fileUrl)"></i>
                </div>
              </div>
            </el-form-item>
          </el-row>
          <el-row v-if="hasReview">
            <el-col :span="24">
              <el-form-item label="复核意见" prop="reviewContent">
                <el-input
                  type="textarea"
                  placeholder="请输入"
                  :rows="3"
                  v-model="ruleForm.reviewContent">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="通知方式" prop="notifyFlag">
              <el-checkbox v-model="ruleForm.notifyFlag">手机短信</el-checkbox>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="`${rectification ? '整改' : '复核'}人`" prop="operatUser">
                <el-select
                  :placeholder="`请选择${rectification ? '整改' : '复核'}人`"
                  clearable
                  filterable
                  :disabled="hasDisabled"
                  :value="userId">
                  <el-option
                    v-for="v in userList"
                    :label="v.userName"
                    :value="v.uuid"
                    :key="v.uuid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="`${rectification ? '整改' : '复核'}日期`" prop="date" required>
                <el-date-picker
                  :placeholder="`请选择${rectification ? '整改' : '复核'}日期`"
                  v-model="ruleForm.date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="date">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="抄送人" prop="cuser">
                <el-select
                  placeholder="请选择抄送人"
                  clearable
                  filterable
                  multiple
                  v-model="ruleForm.cuser">
                  <el-option
                    v-for="v in userList"
                    :label="v.userName"
                    :value="v.uuid"
                    :key="v.uuid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-row>
          <el-form-item label="流程审批记录">
            <el-button
              type="primary"
              icon="el-icon-set-up"
              @click="drawer = true">查看</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <el-drawer
        custom-class="quality-inspection-drawer"
        title="流程审批记录"
        :size="500"
        append-to-body
        :visible.sync="drawer">
        <div v-if="!activities.length" class="empty">
          暂无流程审批记录
        </div>
        <el-timeline v-else>
          <el-timeline-item
            v-for="item in activities"
            :color="typeColors[item.type]"
            :key="item.id">
            <div class="time-line-content">
              <div class="info">
                <p class="title">{{ typeOptions[item.type] || '' }}</p>
                <p>
                  <span class="label">处理人</span>
                  <span class="value">{{ item.operatUserName || '' }}</span>
                </p>
                <p>
                  <span class="label">状态</span>
                  <span class="value">{{ item.status === '1' ? '同意' : '退回' }}</span>
                </p>
              </div>
              <div class="message">
                <el-input
                  type="textarea"
                  disabled
                  :value="item.content"
                  :title="item.content"
                  placeholder="请输入"
                  :rows="4">
                </el-input>
                <span class="time">{{ item.createTime }}</span>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </el-drawer>
    </div>
    <span class="dialog-footer" slot="footer">
      <el-button type="primary" @click="handleCancel">取 消</el-button>
      <el-button
        v-if="hasReview"
        type="danger"
        :loading="loading"
        @click="hanldeSave('2')">
          退回
        </el-button>
      <el-button
        v-if="!hasDetail"
        class="success"
        type="primary"
        :loading="loading"
        @click="hanldeSave('1')">
        {{ rectification ? '提交' : '同意' }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import addLocation from '@/components/corp/addLocation';

export default {
  components: {
    addLocation
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '质量巡检'
    },
    type: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    levels: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: '1' // 1：质量；2：安全
    }
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userId() {
      return this.$store.state.userInfo.uuid;
    },
    // 0：未初审；1：未整改；2：未复核；3：已复核；4：初审失败）
    status() {
      return this.details.status;
    },
    hasDisabled() {
      return this.hasDetail || this.hasReview || this.rectification;
    },
    hasDetail() {
      return this.type === 'detail';
    },
    // 整改
    rectification() {
      return this.type === 'ref';
    },
    // 复核
    hasReview() {
      return this.type === 'review';
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.$nextTick(() => {
          this.getUserList();
          this.getQsInspectionDetail();
        });
        return;
      }
      this.newRectify = {};
      this.newReview = {};
      this.fileLoading = false;
      this.ruleForm = {
        id: '',
        areaId: '',
        areaName: '',
        inspectDate: '',
        severityLevel: '',
        rectifyProblem: '',
        rectifyUser: '',
        operatUser: '',
        rectifyDate: '',
        fileList: [],
        copyUser: '',
        notifyFlag: false,
        // 定位点
        point: {
          lng: '',
          lat: '',
        },
        cuserName: '', // 抄送人
        // 整改
        content: '',
        annexUrl: '',
        annexFileList: [],
        date: '',
        cuser: [],
        // 复核
        reviewContent: ''
      };
    },
    details(data) {
      const keys = Object.keys(this.ruleForm);
      keys.forEach(key => {
        const value = data[key] || '';
        switch (key) {
          case 'operatUser': // 整改(复核)人
            this.ruleForm[key] = this.userId;
            break;
          case 'date':
            this.ruleForm[key] = this.$moment().format('YYYY-MM-DD');
            break;
          case 'cuser':
            this.ruleForm[key] = [];
            break;
          case 'point': // 定位点
            this.ruleForm[key] = {
              lng: data.lng,
              lat: data.lat
            };
            break;
          case 'notifyFlag':
            const notifyObj = {
              '0': this.details.notifyFlag,
              '1': this.details.notifyFlag,
              '2': this.newRectify.notifyFlag,
              '3': this.newReview.notifyFlag,
              '4': this.details.notifyFlag
            };
            this.ruleForm[key] = this.hasDetail
              ? notifyObj[this.status] > 0
              : this.hasReview ? false : value > 0;
            break;
          case 'content': // 整改
            this.ruleForm[key] = this.newRectify.content || '';
            break;
          case 'annexFileList':
            this.ruleForm[key] = this.newRectify.annexUrl
              ? this.newRectify.annexUrl.split(',')
              : [];
            break;
          case 'fileList':
            this.ruleForm[key] = data.rectifyFile
              ? data.rectifyFile.split(',')
              : [];
            break;
          case 'cuserName':
            this.ruleForm[key] = 'cuserName' in this.newReview
              ? this.newReview.cuserName
              : 'cuserName' in this.newRectify
                ? this.newRectify.cuserName
                : this.details.cuserName;
            break;
          default:
            this.ruleForm[key] = value; break;
        }
      });
    }
  },
  data() {
    return {
      drawer: false,
      details: {},
      newRectify: {}, // 最新整改
      newReview: {}, // 最新复核
      userList: [],
      fileLoading: false,
      ruleForm: {
        id: '',
        areaId: '',
        areaName: '',
        inspectDate: '',
        severityLevel: '',
        rectifyProblem: '',
        rectifyUser: '',
        operatUser: '',
        rectifyDate: '',
        fileList: [],
        copyUser: '',
        notifyFlag: false,
        // 定位点
        point: {
          lng: '',
          lat: '',
        },
        cuserName: '', // 抄送人
        // 整改
        content: '',
        annexUrl: '',
        annexFileList: [],
        date: '',
        cuser: [],
        // 复核
        reviewContent: ''
      },
      rules: {
        content: [
          { required: true, message: '请输入整改回复' }
        ],
        // reviewContent: [
        //   { required: true, message: '请输入复核意见' }
        // ],
      },
      activities: [],
      typeOptions: { // 0：初审；1：整改；2：复核
        '0': '检查人检查',
        '1': '整改人整改',
        '2': '检查人复核',
      },
      typeColors: {
        '0': '#3D90FF',
        '1': '#57BA57',
        '2': '#F56263',
      },
    };
  },
  methods: {
    /**
     * 获取质量详情
     */
    async getQsInspectionDetail() {
      if (!this.id) return;
      const { success, data: {
        data
      }} = await this.$Model.getQsInspectionDetail({
        id: this.id
      });
      if (success && data) {
        const {
          qsInspectionFlows,
          newRectify,
          newReview
        } = data;
        this.details = data;
        this.activities = qsInspectionFlows || [];
        if (newRectify) {
          this.newRectify = {
            ...newRectify,
            fileList: newRectify.annexUrl
              ? newRectify.annexUrl.split(',')
              : []
          };
        }
        if (newReview) {
          this.newReview = {
            ...newReview,
            fileList: newReview.annexUrl
              ? newReview.annexUrl.split(',')
              : []
          };
        }
      }
    },
    /**
     * 获取用户列表数据
     */
    async getUserList() {
      const params = {
        pageNum: 1,
        id: this.projectId,
        pageSize: 1000,
        type: '1' // 1：已选择用户；2：未选择用户
      };
      const { success, data: {
        data
      }} = await this.$Model.getProjectUserList(params);
      if (success && data) {
        this.userList = data.list || [];
      }
    },
    // 上传文件
    handleChange(file) {
      this.fileUpload(file.raw);
      return false;
    },
    // 上传文件
    async fileUpload(file) {
      const fm = new FormData();
      fm.append('file', file);
      this.fileLoading = true;
      const { success, data: { data }} = await this.$Model.fileUpload(fm);
      this.fileLoading = false;
      if (success && data) {
        this.ruleForm.annexFileList.push(data);
      }
    },
    // 附件
    files(fileUrl) {
      const fileNames = fileUrl ? fileUrl.match(/([^\/])+\.\w+$/) : '';
      const fileName = Array.isArray(fileNames) ? fileNames[0] : '';
      return {
        name: fileName,
        url: this.$checkUrl(fileUrl),
        hasImg: /\.jpg|\.jpeg|\.png$/.test(fileUrl)
      };
    },
    // 下载文件
    handleUpload(fileUrl) {
      fileUrl && window.open(this.$checkUrl(fileUrl));
    },
    // 删除文件
    async handleRemove(filePath) {
      const index = this.ruleForm.annexFileList.indexOf(filePath);
      if (!this.hasDetail) {
        const { success } = await this.$Model.fileDelete({
          filePath
        });
        if (success) {
          index !== -1 && this.ruleForm.annexFileList.splice(index, 1);
        }
        return;
      }
      index !== -1 && this.ruleForm.annexFileList.splice(index, 1);
    },
    /**
     * 提交
     * @param {String} status 1：同意；2：退回
     */
    hanldeSave(status) {
      this.$refs.ruleForm.validate(async valid => {
        if (valid && this.id) {
          const {
            cuser,
            content = '',
            date = '',
            annexFileList,
            notifyFlag,
            reviewContent = '',
          } = this.ruleForm;
          const params = {
            date,
            status,
            qsId: this.id,
            operatUser: this.userId,
            type: this.details.status,
            notifyFlag: notifyFlag ? '1' : '0',
            content: this.status === '2' ? reviewContent : content,
            annexUrl: this.status === '2'
              ? ''
              : annexFileList && annexFileList.join(',') || '',
            cuser: Array.isArray(cuser) && cuser.join(',') || '',
          };
          this.$emit('submit', params);
        }
      });
    },
    // 取消
    handleCancel() {
      this.$emit('cancel');
    }
  },
};
</script>

<style lang="scss" scoped>
  @import "../../../assets/styles/dialog";
  .add-inspection-detail-modal {
    .form-container {
      padding-right: 20px;
      /deep/ .el-form-item {
        .el-form-item__label {
          color: #fff;
        }
        .el-select, .el-date-editor {
          width: 100%;
        }
        .el-input, .el-textarea {
          &.is-disabled {
            input, textarea {
              background-color: $disabledBg;
              color: #fff;
              border-color: transparent;
            }
          }
        }
        .tip {
          margin-left: 20px;
        }
      }
      .location-form {
        /deep/ .add-location-comp {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          .el-input {
            margin-right: 50px;
          }
        }
      }
      .tree-form {
        /deep/ .el-form-item__content {
          position: relative;
          .menu-filter-tree {
            position: absolute;
            top: 38px;
            left: 1px;
            width: 100%;
            max-height: 300px;
            z-index: 2;
            background-color: #fff;
            border: 1px solid #f1f1f1;
            border-top-color: transparent;
            box-shadow: 0 2px 8px 0 #bbb;
            border-radius: 4px;
            overflow: auto;
          }
        }
      }
      .file-list {
        width: 100%;
        max-height: 120px;
        padding-right: 20px;
        overflow-y: auto;
        .file-text {
          width: 100%;
          display: flex;
          align-items: center;
          cursor: pointer;
          transition: color .2s;
          .file-name {
            max-width: calc(100% - 100px);
            display: inline-block;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            padding-right: 20px;
          }
          &:hover {
            color: $mainColor;
          }
        }
      }
      .el-checkbox {
        color: #fff;
      }
    }
  }

  /deep/.el-drawer__wrapper {
    .quality-inspection-drawer {
      .el-drawer__body {
        padding: 20px 10px;
        .empty {
          width: 100%;
          height: 80px;
          text-align: center;
          line-height: 80px;
          color: $disabledBg;
        }
        .el-timeline {
          padding: 0 10px;
          .time-line-content {
            width: 100%;
            display: flex;
            justify-content: space-between;
            .info {
              width: 200px;
              display: flex;
              flex-direction: column;
              p {
                margin-bottom: 15px;
                &.title {
                  font-weight: bold;
                }
                .label {
                  width: 80px;
                  display: inline-block;
                }
                .value {
                  color: $lightBtnBg;
                }
              }
            }
            .message {
              flex: 1;
              position: relative;
              .el-textarea {
                &.is-disabled {
                  textarea {
                    border-color: transparent;
                    padding-bottom: 20px;
                  }
                }
                textarea {
                }
              }
              .time {
                position: absolute;
                bottom: 4px;
                right: 20px;
                color: $disabledBg;
              }
            }
          }
        }
      }
    }
  }
</style>
